<template>
	<u-popup :show="show" @close="emits('close')" mode="bottom" round="8" closeable>
		<view>
			<u-gap height="50rpx"></u-gap>
			<view class="content">
				<view class="item border_b flex-c-s">
					<view class="" style="margin-bottom: 20rpx;">
						修改头像
					</view>
					<button class="avatar" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image class="avatar" :src="$ossurl+formData.avatar" @error="imgError" mode=""></image>
					</button>
				</view>
				<view class="item border_b flex-c-s">
					<view class="" style="margin-bottom: 20rpx;">
						修改昵称
					</view>
					<input type="nickname" class="u-p-l-20" style="text-align: right;" :value="formData.nickname"
						placeholder="请输入昵称" @change="getNickname" />
				</view>
			</view>
			<u-gap height="20rpx"></u-gap>
			<u-button @click="jump" :color="$main_color" style="width: 96%;margin: 0 auto;" text="修改"></u-button>
			<u-gap height="160rpx"></u-gap>
		</view>
	</u-popup>
</template>
<script setup>
	import {
		ref,
		watch,
		nextTick
	} from 'vue'

	const emits = defineEmits(['success', 'close'])
	const props = defineProps(['show'])

	const DATA_STORE = uni.$store('data')
	const formData = ref({
		nickname: '',
		avatar: '',

	})
	watch(() => DATA_STORE.userInfo,
		(n) => {
			formData.value = {
				nickname: DATA_STORE.userInfo.nickname,
				avatar: DATA_STORE.userInfo.avatar,
			}
		}, {
			deep: true,
			immediate: true
		})

	const imgError = (err) => {
		// DATA_STORE.userInfo.avatar = '/static/base/wx_logo.png'
		// DATA_STORE.setUserInfo(DATA_STORE.userInfo)
	}
	const onChooseAvatar = async (e) => {
		let res = await uni.$uploadImg(e.detail.avatarUrl)
		formData.value.avatar = res.data.url
	}
	const getNickname = (e) => {
		formData.value.nickname = e.detail.value
	}

	const jump = async () => {
		if (!formData.value.nickname) {
			return uni.showToast({
				title: '请填写昵称',
				icon: 'none'
			})
		}
		uni.$u.http.post('/user/profile', {
			...formData.value
		}).then(complete)

	}
	const complete = (data) => {
		uni.showToast({
			title: data.msg,
			icon: 'none'
		})
		DATA_STORE.userInfo.nickname = formData.value.nickname
		DATA_STORE.userInfo.avatar = formData.value.avatar
		DATA_STORE.setUserInfo(DATA_STORE.userInfo)
		emits('success')
	}
</script>

<style scoped lang="scss">

	.content {
		background-color: white;
		width: 100%;
		button {
			padding: 0;
			margin: 0;
			line-height: 1;
		}
		
		button::after {
			border: none;
		}
		
		
		.avatar {
			width: 40px;
			height: 40px;
			flex: 0 0 auto;
			border-radius: 50%;
			overflow: hidden;
		
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.item {
			width: 100%;
			padding: 0 32rpx;
			height: 60px;
			font-size: 14px;
		}

		.border_b {
			border-bottom: 1rpx solid #e7e7e7;
		}
	}


</style>